package com.acceptable.qucun.user.service;

import com.acceptable.qucun.generic.util.result.error.UserErrorResult;
import com.acceptable.qucun.user.entity.User;
import com.acceptable.qucun.user.exception.UserOperationException;
import com.acceptable.qucun.user.mapper.UserMapper;
import com.acceptable.qucun.user.service.impl.UserDatabaseOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginVerifyService implements UserDetailsService {
    @Autowired private UserMapper userMapper;
    @Autowired private UserDatabaseOperation userDataOperation;

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    public BCryptPasswordEncoder getEncoder() {
        return encoder;
    }

    /**
     *  根据传来的用户帐号email查询是否有该用户
     *  若存在 则创建UserDetails对象 便于自定义验证用户是否登录
     */
    @Override
    public UserDetails loadUserByUsername(String email) {
        List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
        System.out.println("执行鉴权");
        User user = userMapper.selectByEmail(email);
        // 被删除的状态
        if(user == null || user.getDeleted()){
            if(user != null){
                userDataOperation.deleteUserByEmail(email);
            }
            throw new UserOperationException(UserErrorResult.ACCOUNT_NOT_EXIST_ERROR);
        }

        String password_data = user.getPassword();
        String username = String.valueOf(user.getUserId());
//        System.out.println(password_data);

        // 数据库中密码base64加密 二次加密进行判断
        String password = this.encoder.encode(password_data);
        return new org.springframework.security.core.userdetails.User(username, password, grantedAuthorityList);
    }

}
